﻿using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace UFIDA.U9.WSS.ProxyService.Json
{
    /// <summary>
    ///     自定义日期转换器
    ///     当类型不是可空类型时，当日期等于null或者等于空时,自动返回DateTime.MinValue
    /// </summary>
    public class CustIsoDateTimeConverter : IsoDateTimeConverter
    {
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
            JsonSerializer serializer)
        {
            bool nullable = IsNullableType(objectType);
            if (nullable) base.ReadJson(reader, objectType, existingValue, serializer);
            if (reader.TokenType == JsonToken.Null)
            {
                return DateTime.MinValue;
            }

            if (reader.TokenType != JsonToken.String)
                return base.ReadJson(reader, objectType, existingValue, serializer);
            string dateText = reader.Value.ToString();
            return string.IsNullOrEmpty(dateText)
                ? DateTime.MinValue
                : base.ReadJson(reader, objectType, existingValue, serializer);
        }

        public static bool IsNullableType(Type t)
        {
            if (t == null)
                throw new ArgumentNullException("t");
            return t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>);
        }
    }
}